var util = require('../../utils/util.js');
var api = require('../../config/api.js');
Page({
    data: {
        // 设备信息
        isIphoneX: 0,
        id: 0,
        // 团单信息
        teamInfo: {},
        // 购买商品人员列表
        userTeamProductList: [],
        // 已购买人数
        userCount: 0,
        // 用户信息
        userInfo: {},
        // 商品简介弹出层
        goodsPopup: false,
        // 拿到的商品列表
        goodsList: [],
        // 已选商品弹出框
        goodsNumPopup: false,
        //   已选商品总数量
        productGoodsNumber: 0,
        //   已选商品总钱数
        productGoodsMonery: 0.00,
        //  要查看的商品信息
        goods: {},
        // loading 控制加载图标的位置
        sysHeight: 0,
        // 控制加载
        loading: 0,
        // 商品sku选择弹框
        selectGoodsSku: false,
        // 要选取的商品信息
        selectGoodsInfo: {},
        // 判断需要选择规格的商品规格是否选择完整
        skuPriceVisible: false,
        // 单样商品选取的数量
        number: 1,
        // 选中的商品规格信息
        checkedSkuProductInfo: {},
        // 选中商品sku的 属性名拼接
        checkedSkuProductName: '',
        // 欲购买的商品列表
        wantBuyGoods: [],
        // 下单提示弹出框的显隐
        BuyRemindShow: false,
        // 消息提示
        inviteToast: 1,
        // 判断该团单是否已经删除
        orderDeleted:0,
    },
    onLoad: function (options) {
        let id = options.id
        if (id == 'undefined' || id == '') {
            wx.showToast({
                title: '该团购不存在',
                icon: 'none',
                duration: 2000
            })
        } else {
            id = options.id;
            this.getTeamOrderInfo(id);
        }
        this.setData({
            id: id, // 这个是订单id
            valueId: id,
        });
        // 获取设备信息
        let phone = wx.getStorageSync('isIphoneX')
        if (phone) {
            this.setData({
                isIphoneX: 1
            })
        }

    },
    onShow: function () {
        let info = wx.getSystemInfoSync();
        let sysHeight = info.windowHeight - 100;
        this.setData({
            sysHeight: sysHeight,
        });
        this.countDown();
    },
    // 定时器清除气泡提示
    countDown() {
        let that=this
        var time = setTimeout(function(){
            that.setData({
                inviteToast:0
            })
            clearTimeout(time);
        },10000)
    },
    // 确认购买须知
    BuyRemind() {
        let that = this;
        let userID = wx.getStorageSync('userID')
        let goods = that.data.wantBuyGoods;
        util.requestApi(api.teamPlaceOrder, {
            teamOrderID: that.data.id,
            userID: userID,
            productList: goods
        }).then(function (res) {
            if (res.code == 200) {
                let con = res.content
                wx.requestPayment({
                    timeStamp: con.timeStamp,
                    nonceStr: con.nonceStr,
                    package: con.package,
                    signType: con.signType,
                    paySign: con.paySign,
                    success(res) {
                        wx.showToast({
                            title: '下单成功',
                            icon: 'success',
                            duration: 2000
                        })
                        wx.navigateTo({
                            url: '../ucenter/team-order/team-order',
                        })
                    },
                    fail(res) {
                        wx.showToast({
                            title: '下单失败',
                            icon: 'none',
                            duration: 2000
                        })
                    }
                })
            } else {
                wx.showToast({
                    title: res.msg,
                    icon: 'none',
                    duration: 2000
                })
            }
        })
    },
    // 取消购买须知
    BuyRemindClose() {
        this.setData({
            BuyRemindShow: false
        })
    },
    // 打开商品选择弹框
    openSelectGood(e) {
        let index = e.currentTarget.dataset.index;
        let skuList = this.data.teamInfo.productList[index];
        for (let i = 0; i < skuList.length; i++) {
            for (let j = 0; j < skuList[i].param; j++) {
                skuList[i].param[j].checked = false;
            }
        }
        this.setData({
            selectGoodsSku: !this.data.selectGoodsSku,
            selectGoodsInfo: skuList
        })
    },
    // 判断规格是否选择完整
    changeSpecInfo: function () {
        // 拿到规格长度 判断下面选中的规格是否选择完整
        let skuListLength = this.data.selectGoodsInfo.skuList.length
        // 拿到sku对应查询列表
        let skuListInfo = this.data.selectGoodsInfo.skuInfo
        // 拿到选中的值
        let checkedSkuID = this.getCheckedSpecValue();
        // 判断sku是否选择完整
        if (skuListLength === checkedSkuID.skuID.length && skuListLength === checkedSkuID.skuPID.length) {
            // 判断选择的规格
            for (let i = 0; i < skuListInfo.length; i++) {
                if (skuListInfo[i].skuID.toString() === checkedSkuID.skuID.toString() && skuListInfo[i].skuPID.toString() === checkedSkuID.skuPID.toString()) {
                    // 有该规格的商品 展示该规格商品信息
                    this.setData({
                        checkedSkuProductInfo: skuListInfo[i],
                        skuPriceVisible: true
                    })
                }
            }
        } else {
            this.setData({
                skuPriceVisible: false
            })
        }
    },
    //获取选中的规格信息
    getCheckedSpecValue: function () {
        let checkedValues = {
            skuID: [],
            skuPID: []
        };
        let checkedNameList = [];
        let specificationList = this.data.selectGoodsInfo.skuList;
        for (let i = 0; i < specificationList.length; i++) {
            for (let j = 0; j < specificationList[i].param.length; j++) {
                if (specificationList[i].param[j].checked) {
                    checkedValues.skuID.push(specificationList[i].param[j].id)
                    checkedValues.skuPID.push(specificationList[i].param[j].parentID)
                    checkedNameList.push(specificationList[i].param[j].name)
                }
            }
        }
        this.setData({
            checkedSkuProductName: checkedNameList.join('&')
        })
        return checkedValues;
    },
    // 选择规格
    clickSkuValue: function (event) {
        let index = event.currentTarget.dataset.index;
        let parentIndex = event.currentTarget.dataset.parentIndex;
        let goods = this.data.selectGoodsInfo
        for (let i = 0; i < goods.skuList.length; i++) {
            if (i == parentIndex) {
                for (let j = 0; j < goods.skuList[i].param.length; j++) {
                    if (j == index) {
                        if (goods.skuList[i].param[j].checked) {
                            goods.skuList[i].param[j].checked = false
                        } else {
                            goods.skuList[i].param[j].checked = true
                        }
                    } else {
                        goods.skuList[i].param[j].checked = false;
                    }
                }
            }
        }
        this.setData({
            selectGoodsInfo: goods
        })
        this.changeSpecInfo()
    },
    // 确认选择添加该商品
    selectPdtSkuBtn() {
        // 判断是否登录，如果没有登录，则登录
        util.loginNow();
        let userInfo = wx.getStorageSync('userInfo');
        if (userInfo == '') {
            return false;
        }
        // 判断当前要选择的产品需不需要选择规格
        if (this.data.selectGoodsInfo.skuList.length > 0) {

            // 判断规格是否选择完整
            if (!this.data.skuPriceVisible) {
                wx.showToast({
                    image: '/images/icon/icon_error.png',
                    title: '请选择规格',
                });
                return false;
            }
            // 验证库存
            if (this.data.checkedSkuProductInfo.stock < this.data.number) {
                //要买的数量比库存多
                wx.showToast({
                    image: '/images/icon/icon_error.png',
                    title: '库存不足',
                });
                return false;
            }
            let productInfo = {
                productName: this.data.selectGoodsInfo.productName,
                titleImg: this.data.selectGoodsInfo.titleImg,
                count: this.data.number,
                money: (this.data.checkedSkuProductInfo.price * this.data.teamInfo.discount / 100).toFixed(2),
                productID: this.data.checkedSkuProductInfo.productID,
                middleID: this.data.checkedSkuProductInfo.middleID,
                skuID: this.data.checkedSkuProductInfo.skuID,
                skuPID: this.data.checkedSkuProductInfo.skuPID,
                skuName: this.data.checkedSkuProductName
            }
            this.setData({
                selectGoodsSku: false,
                wantBuyGoods: this.data.wantBuyGoods.concat(productInfo),
            })
            this.resetSelectSkuProduct()
            this.sumMonery()
        } else {
            if (this.data.goods.inventory < this.data.number) {
                //要买的数量比库存多
                wx.showToast({
                    image: '/images/icon/icon_error.png',
                    title: '库存不足',
                });
                return false;
            }
            let productInfo = {
                productName: this.data.selectGoodsInfo.productName,
                titleImg: this.data.selectGoodsInfo.titleImg,
                count: this.data.number,
                money: (this.data.selectGoodsInfo.price * this.data.teamInfo.discount / 100).toFixed(2),
                productID: this.data.selectGoodsInfo.productID,
                middleID: null,
                skuID: null,
                skuPID: null,
                skuName: null
            }
            this.setData({
                selectGoodsSku: false,
                wantBuyGoods: this.data.wantBuyGoods.concat(productInfo),
            })
            this.resetSelectSkuProduct()
            this.sumMonery()
        }
    },
    // 点击减少商品数量
    cutNumber: function () {
        this.setData({
            number: (this.data.number - 1 > 1) ? this.data.number - 1 : 1
        });
    },
    // 点击增加商品数量
    addNumber: function () {
        this.setData({
            number: Number(this.data.number) + 1
        });
    },
    // 删除欲购买的商品
    delSelectProduct(e) {
        let index = e.currentTarget.dataset.index;
        let wantBuyGoods = this.data.wantBuyGoods;
        wantBuyGoods.splice(index, 1);
        this.setData({
            wantBuyGoods: wantBuyGoods
        })
        this.sumMonery();
    },
    // 打开商品简介弹出层
    onClickButton(e) {
        let index = e.currentTarget.dataset.index;
        let goodsList = this.data.goodsList;

        this.setData({
            goods: goodsList[index],
            goodsPopup: !this.data.goodsPopup
        })
    },
    // 打开选择商品数量弹出层
    openGoodsNumPopup() {
        this.setData({
            goodsNumPopup: !this.data.goodsNumPopup
        })
    },
    // 关闭弹出层
    onCloseSku() {
        this.setData({
            selectGoodsSku: false
        });
        this.resetSelectSkuProduct()
    },
    // 重置选中的商品信息
    resetSelectSkuProduct() {
        let goods = this.data.selectGoodsInfo
        for (let i = 0; i < goods.skuList.length; i++) {
            for (let j = 0; j < goods.skuList[i].param.length; j++) {
                goods.skuList[i].param[j].checked = false;
            }
        };
        this.setData({
            skuPriceVisible: false,
            selectGoodsInfo: goods,
            number: 1,
            checkedSkuProductInfo: {},
            checkedSkuProductName: '',
        })
    },
    // 关闭弹出层
    onClose() {
        this.setData({
            goodsPopup: false,
            goodsNumPopup: false,
            selectGoodsSku: false
        })

    },
    // 计算商品的总数量与总价格和更新选中的商品列表
    sumMonery() {
        let goodsMonery = 0.00;
        let goodsNum = 0;
        let goods = this.data.wantBuyGoods
        for (let i = 0; i < goods.length; i++) {
            goodsMonery += goods[i].count * goods[i].money
            goodsNum += goods[i].count;
        }
        this.setData({
            productGoodsMonery: goodsMonery.toFixed(2),
            productGoodsNumber: goodsNum
        })
    },
    closeAttr: function () {
        this.setData({
            openAttr: false,
        });
    },
    // 提交购买
    buyGoods() {
        let that = this;
        let r = util.loginNow();
        if (r == true) {
            let userID = wx.getStorageSync('userID')
            let goods = that.data.wantBuyGoods;
            if (goods.length == 0) {
                wx.showToast({
                    title: '未选择商品',
                    icon: 'none',
                    duration: 2000
                })
                return;
            }
            // 判断用户是否填写地址
            util.requestApi(api.getUserAddress, {
                userID: userID
            }).then(function (res) {
                if (res.content.length == 0) {
                    wx.showToast({
                        title: '请添加地址信息，方便团长与您联系',
                        icon: 'none',
                        duration: 2000
                    })
                    wx.navigateTo({
                        url: '../ucenter/address-detail/index?id=' + 0,
                    })
                } else {
                    // 购买确认提示框
                    that.setData({
                        BuyRemindShow: true
                    })
                }
            })
        }
    },
    // 获取指定团购订单的详细信息
    getTeamOrderInfo(id) {
        let that = this;
        util.requestApi(api.getTeamOrderInfo, {
            teamOrderID: parseInt(id)
        }).then(function (res) {
            if (res.code == 200) {
                that.setData({
                    teamInfo: res.content.teamInfo,
                    userCount: res.content.userCount,
                    userTeamProductList: res.content.userTeamProductList,
                    goodsList: res.content.teamInfo.productList,
                    loading: 1,
                    orderDeleted:0
                })
            }else if(res.code==-2){
                that.setData({
                    loading: 1,
                    orderDeleted:1
                })
            }
        })
    },
    onPullDownRefresh: function () {
        wx.showNavigationBarLoading()
        this.getTeamOrderInfo(this.data.id);
        this.setData({
            loading: 0,
        });
        wx.hideNavigationBarLoading() //完成停止加载
        wx.stopPullDownRefresh() //停止下拉刷新
    },
    // 分享配置
    onShareAppMessage: function (res) {
        let id = this.data.id;
        let name = this.data.teamInfo.title;
        let image = this.data.teamInfo.titleImg;
        return {
            title: name,
            path: '/pages/goods-team/goods-team?id=' + id,
            imageUrl: image
        }
    },
})